package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.ParsedCardinality;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: stone
 * @date: Created by 2022/11/25 13:46
 * @version: 1.0.0
 * @pakeage: com.ruoyi.web.controller.system
 */
@RestController
@RequestMapping("/es")
@Api(value = "es查询数据")
@Slf4j
public class ElasticsearchController {


    @Autowired
    RestHighLevelClient client;

    @GetMapping("/count")
    @ApiOperation("统计")
    public AjaxResult count() throws IOException {
        // 创建查询请求
        SearchRequest request = new SearchRequest();
        request.indices("shiguiwu");
        // 创建查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 根据年龄去重，并起别名为：u_age
        builder.aggregation(AggregationBuilders.cardinality("ip_count").field("name"));
        request.source(builder);
        // 查询
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        ParsedCardinality cardinality = (ParsedCardinality) aggregations.asList().get(0);
        long count = cardinality.getValue();
        log.info("去重后的总数：" + count);

        return AjaxResult.success(count);

    }


    @GetMapping("/count2")
    @ApiOperation("统计2")
    public AjaxResult count2() throws IOException {
        // 创建查询请求
        CountRequest request = new CountRequest("shiguiwu");
        // 创建查询条件
        //SearchSourceBuilder builder = new SearchSourceBuilder();
        // 根据年龄去重，并起别名为：u_age
        //builder.aggregation(AggregationBuilders.cardinality("ip_count").field("name"));
        //request.source(builder);


        //queryBuilder.must(QueryBuilders.rangeQuery( "name.keyword"));

        //queryBuilder.query(QueryBuilders.rangeQuery(rangeName).gte(gte).lte(lte));


        //builder.query(queryBuilder);

        //builder.query(QueryBuilders.)


        RangeQueryBuilder age = QueryBuilders.rangeQuery("age").gte(12).lte(189);
        String[] arr = {"shiguiwu", "zhoudongxiu"};
        for (int i = 0; i < arr.length; i++) {

            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            //BoolQueryBuilder q2 = QueryBuilders.boolQuery();

            BoolQueryBuilder q1 = QueryBuilders.boolQuery();
            q1.must().add(age);
            queryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.termsQuery("name", arr[i], "")));

            queryBuilder.must(q1);

            //QueryBuilders.boolQuery().must().add(age);

            request.query(queryBuilder);

            // 查
            CountResponse count1 = client.count(request, RequestOptions.DEFAULT);

            long count2 = count1.getCount();

            log.info("去重后的总数：" + count2);
        }


        //Aggregations aggregations = response.getAggregations();
        //ParsedCardinality cardinality = (ParsedCardinality) aggregations.asList().get(0);
        //long count = cardinality.getValue();


        return AjaxResult.success(1);

    }


    @GetMapping("/list")
    @ApiOperation("分页查询")
    public AjaxResult list() {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder.must(QueryBuilders.matchAllQuery())
        //        .filter(QueryBuilders.rangeQuery("publish_time").gt(time.getTime()));
        try {
            searchSourceBuilder.query(builder)
                    //.sort("id", SortOrder.ASC)
                    //.sort("publish_time", SortOrder.ASC)
                    .from(0)
                    .size(10);
            SearchRequest searchRequest = new SearchRequest("shiguiwu").source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = searchResponse.getHits().getHits();
            if (hits.length > 0) {
                List<SearchHit> searchHits = Arrays.asList(hits);
                searchHits.forEach(e -> {
                    Map<String, Object> sourceAsMap = e.getSourceAsMap();

                    String sourceAsString = e.getSourceAsString();//json
                });
                return AjaxResult.success(searchHits);
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("doc分页查询异常:{} ", e);
        }
        return null;


    }
}
